import { useIntl } from '@umijs/max';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts/core';
import React, { useEffect } from 'react';
import { fitChartSize, formatPower } from '../utils/tools';

// 定义数据类型
export interface StationChargeData {
  date: string;
  chargeEnergy: number | string | null;
  dischargeEnergy: number | string | null;
}

// 定义组件属性类型
interface StationChargeDataProps {
  data: StationChargeData[];
  onUnitChange: (unit: string) => void;
  dataType: string; // 新增的参数
}

// 自定义函数来调整 Y 轴的刻度值
const adjustYAxisValue = (value: number) => {
  const magnitude = Math.pow(10, Math.floor(Math.log10(Math.abs(value))));
  const normalizedValue = Math.abs(value) / magnitude;
  let adjustedValue;

  if (normalizedValue >= 9) {
    adjustedValue = 10;
  } else if (normalizedValue >= 8) {
    adjustedValue = 9;
  } else if (normalizedValue >= 7) {
    adjustedValue = 8;
  } else if (normalizedValue >= 6) {
    adjustedValue = 7;
  } else if (normalizedValue >= 5) {
    adjustedValue = 6;
  } else if (normalizedValue >= 4) {
    adjustedValue = 5;
  } else if (normalizedValue >= 3) {
    adjustedValue = 4;
  } else if (normalizedValue >= 2) {
    adjustedValue = 3;
  } else if (normalizedValue >= 1) {
    adjustedValue = 2;
  } else {
    adjustedValue = 1;
  }

  // 增加一个因子以扩大刻度间隔，并向上舍入到最接近的整数
  return {
    value: Math.ceil((adjustedValue * magnitude * 1.5) / magnitude) * magnitude,
  };
};

// 创建组件
const StationChargeOverview: React.FC<StationChargeDataProps> = ({
  data,
  onUnitChange,
  dataType,
}) => {
  const intl = useIntl();
  // 处理数据，将 null 和 '--' 统一设置为 0
  const processedData = data.map((item) => {
    const chargeEnergy =
      item.chargeEnergy === null || item.chargeEnergy === '--' ? 0 : item.chargeEnergy;
    const dischargeEnergy =
      item.dischargeEnergy === null || item.dischargeEnergy === '--' ? 0 : item.dischargeEnergy;

    return {
      ...item,
      chargeEnergy: parseFloat(formatPower(chargeEnergy, false, 'GWh').value),
      dischargeEnergy: parseFloat(formatPower(dischargeEnergy, false, 'GWh').value),
    };
  });

  // 提取数据并格式化日期
  const dates = processedData.map((item) => {
    const [year, month, day] = item.date.split('-');
    if (dataType === 'year') {
      return year; // 年度显示年份
    } else if (dataType === 'month') {
      return `${year.slice(2)}/${month}`; // 月度显示 年/月
    } else {
      return `${month}/${day}`; // 日期显示 月/日
    }
  });

  const chargeEnergy = processedData.map((item) => item.chargeEnergy as number); // 处理后的数据不包含 null 或 '--'
  const dischargeEnergy = processedData.map((item) => item.dischargeEnergy as number); // 处理后的数据不包含 null 或 '--'

  // 计算最大值和最小值
  const maxChargeEnergy = Math.max(...chargeEnergy);
  const maxDischargeEnergy = Math.max(...dischargeEnergy);
  const minChargeEnergy = Math.min(...chargeEnergy);
  const minDischargeEnergy = Math.min(...dischargeEnergy);

  const maxEnergy = Math.max(maxChargeEnergy, maxDischargeEnergy);
  const minEnergy = Math.min(minChargeEnergy, minDischargeEnergy);

  // 计算 Y 轴的最大值和刻度间隔
  const yAxisMaxInfo = adjustYAxisValue(maxEnergy);
  const yAxisMax = maxEnergy === 0 ? 0.1 : yAxisMaxInfo.value; // 添加最小刻度值

  // 确定 Y 轴的最小值
  const yAxisMin = minEnergy < 0 ? -yAxisMax : 0;

  // 使用 useEffect 在组件挂载时调用 onUnitChange
  useEffect(() => {
    onUnitChange('GWh');
  }, ['GWh', onUnitChange]);

  // 配置 ECharts 选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      backgroundColor: 'rgba(3, 25, 54, 0.7)', // 设置背景颜色和透明度
      borderColor: '#4c8fce', // 设置边框颜色
      borderWidth: 1, // 设置边框宽度
      textStyle: {
        color: '#C4D4F1', // 设置文字颜色
        fontSize: fitChartSize(12),
      },
      formatter: function (params: any) {
        const date = new Date(data[params[0].dataIndex].date);
        let formattedDate = '';
        if (dataType === 'year') {
          formattedDate = `${date.getFullYear()}`;
        } else if (dataType === 'month') {
          formattedDate = `${date.getFullYear()}-${date.getMonth() + 1}`;
        } else {
          formattedDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
        }

        const charge = params.find(
          (param: any) => param.seriesName === intl.formatMessage({ id: 'bigdata.charge' }),
        );
        const discharge = params.find(
          (param: any) => param.seriesName === intl.formatMessage({ id: 'bigdata.discharge' }),
        );

        const formattedCharge = formatPower(charge.value * 1000000, false, 'GWh'); // 恢复原始值再转换
        const formattedDischarge = formatPower(discharge.value * 1000000, false, 'GWh'); // 恢复原始值再转换

        return `
          <div>
            <div>${formattedDate}</div>
            <div style="display: flex; align-items: center;">
              <span style="display: inline-block; width: 10px; height: 10px; background: linear-gradient(0deg, rgba(255,252,0,1) 0%, rgba(255,252,0,1) 100%); border-radius: 50%; margin-right: 5px;"></span>
              ${charge.seriesName}: ${formattedCharge.value} ${formattedCharge.unit}
            </div>
            <div style="display: flex; align-items: center;">
              <span style="display: inline-block; width: 10px; height: 10px; background: linear-gradient(0deg, #67C23A 40%, #67C23A 100%); border-radius: 50%; margin-right: 5px;"></span>
              ${discharge.seriesName}: ${formattedDischarge.value} ${formattedDischarge.unit}
            </div>
          </div>`;
      },
    },
    legend: {
      data: [
        intl.formatMessage({ id: 'bigdata.charge' }),
        intl.formatMessage({ id: 'bigdata.discharge' }),
      ],
      textStyle: {
        color: '#5381CC',
        fontSize: fitChartSize(12),
      },
      top: 0,
      right: 0,
      icon: 'circle', // 自定义图例形状
      itemWidth: 12, // 设置图例项的宽度
      itemHeight: 12, // 设置图例项的高度
    },
    grid: {
      left: '3%', // 调整左边距确保 Y 轴显示
      right: '3%', // 调整右边距确保 Y 轴显示
      bottom: '0%',
      top: '20%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: dates,
        axisLine: {
          lineStyle: {
            color: 'rgba(55,255,249,1)',
          },
        },
        axisLabel: {
          textStyle: {
            color: '#77a5f1',
            interval: 0, // 确保显示所有标签
            align: 'center', // 确保标签居中对齐
            fontSize: fitChartSize(12),
          },
        },
        axisTick: {
          alignWithLabel: true, // 确保刻度与标签对齐
        },
        splitLine: {
          show: false,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        min: yAxisMin,
        max: yAxisMax,
        splitNumber: 5, // 刻度数量
        axisLabel: {
          color: '#77a5f1',
          formatter: function (value: number) {
            if (value === 0) {
              return '0';
            } else {
              const formattedValue = formatPower(value * 1000000, false, 'GWh'); // 恢复原始值再转换
              return `${formattedValue.value}`;
            }
          },
          fontSize: fitChartSize(12),
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(55,255,249,1)',
          },
        },
        splitLine: {
          lineStyle: {
            type: 'dotted', // 设置为虚线
            color: 'rgba(53, 78, 114, 0.3)', // 颜色可根据需要调整
          },
        },
      },
    ],
    series: [
      {
        name: intl.formatMessage({ id: 'bigdata.charge' }),
        type: 'bar',
        barWidth: 10,
        itemStyle: {
          barBorderRadius: [20, 20, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#FFD60C' },
            { offset: 1, color: '#FFD60C' },
          ]),
        },
        data: chargeEnergy,
      },
      {
        name: intl.formatMessage({ id: 'bigdata.discharge' }),
        type: 'bar',
        barWidth: 10,
        barGap: '-100%',
        itemStyle: {
          barBorderRadius: [20, 20, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0.4, color: '#67C23A' },
            { offset: 1, color: '#67C23A' },
          ]),
        },
        data: dischargeEnergy,
      },
    ],
  };

  return <ReactECharts option={option} style={{ width: '100%', height: fitChartSize(150) }} />;
};

export default StationChargeOverview;
